package com.design.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.design.config.CommonException;
import com.design.dao.entity.Container;
import com.design.dao.entity.Template;
import com.design.dao.mapper.ContainerMapper;
import com.design.model.PageResult;
import com.design.service.ContainerService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

@Service
public class ContainerServiceImpl implements ContainerService {

    @Autowired
    private ContainerMapper containerMapper;

    @Override
    public PageResult<List<Container>> queryByPage(String containerNum, Integer pageNum, Integer pageSize) {
        QueryWrapper<Container> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete", 0);
        wrapper.orderByDesc("id");
        if (StringUtils.isNoneBlank(containerNum)) {
            wrapper.eq("container_num", containerNum);
        }
        Page<Container> responseList = containerMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
        return new  PageResult<>(responseList.getRecords(), responseList.getTotal());
    }

    @Override
    public void edit(Container container) {
        container.setIsDelete((byte)0);
        if(null == container.getId()){
            QueryWrapper<Container> containerQueryWrapper = new QueryWrapper<>();
            containerQueryWrapper.eq("container_num", container.getContainerNum());
            List<Container> containers = containerMapper.selectList(containerQueryWrapper);
            if (!CollectionUtils.isEmpty(containers)) {
                throw new CommonException("集装箱编号已存在，请勿重复录入");
            }

            container.setCreateTime(new Date());
            containerMapper.insert(container);
            return;
        }
        containerMapper.updateById(container);
    }

    @Override
    public void remove(Integer id) {
        containerMapper.deleteById(id);
    }
}
